package view.controller;

import common.Group;
import common.Message;
import common.NowUser;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import server.ClientConnServer;

import javax.swing.*;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.BrokenBarrierException;

public class ExitGroupController implements Initializable {
    public ImageView exitclose;
    public Button exittrue;
    public Button exitfalse;
    public Label exitgroupid;

    public void onexitfalse(ActionEvent actionEvent) {
        Stage stage = (Stage) exitfalse.getScene().getWindow();
        stage.close();
    }

    public void onexittrue(ActionEvent actionEvent) throws IOException, BrokenBarrierException, InterruptedException {
        Group group = new Group();
        NowUser common = new NowUser();
        Message msg = new Message();
        group.setuserid(common.getUser().getId());
        group.setGroupid(common.getGroup().getGroupid());
        group.setGroupid(exitgroupid.getText());
        System.out.println("即将被退出群聊的id:" + common.getGroup().getGroupid());
        msg.setGroup(group);
        msg.setType("exitgroup");
        NowUser.exitgroup=false;
        new ClientConnServer().sendinfo(msg);
        NowUser.cyclicBarrier.reset();
        NowUser.cyclicBarrier.await();
        if(NowUser.exitgroup) {
            System.out.println("退出群聊");
            JOptionPane.showMessageDialog(null, "退群成功", "提示", JOptionPane.PLAIN_MESSAGE);
            Stage stage = (Stage) exittrue.getScene().getWindow();
            stage.close();
        } else{
            JOptionPane.showMessageDialog(null, "退群失败", "提示", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void toexitclose(MouseEvent mouseEvent) {
        Stage stage = (Stage) exitclose.getScene().getWindow();
        stage.close();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        exitgroupid.setText(NowUser.group.getGroupid());
    }
}
